package team.nine.kuaichezuche.service.impl;

import org.springframework.stereotype.Service;
import team.nine.kuaichezuche.service.RedisService;
import team.nine.kuaichezuche.service.VerificationCodeService;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    
    @Resource
    private RedisService redisService;
    
    // 验证码有效期（分钟）
    private static final long CODE_EXPIRATION = 30;
    
    // 验证码长度
    private static final int CODE_LENGTH = 6;
    
    // Redis存储键前缀
    private static final String CODE_PREFIX = "verification:code:";
    
    @Override
    public String generateVerificationCode(String key) {
        // 生成6位随机数字验证码
        String code = generateRandomCode(CODE_LENGTH);
        
        // 构建Redis存储键
        String redisKey = CODE_PREFIX + key;
        
        // 存储验证码到Redis，设置30分钟过期
        redisService.set(redisKey, code, CODE_EXPIRATION, TimeUnit.MINUTES);
        
        return code;
    }
    
    @Override
    public boolean verifyCode(String key, String code) {
        if (key == null || code == null) {
            return false;
        }
        
        // 构建Redis存储键
        String redisKey = CODE_PREFIX + key;
        
        // 从Redis获取验证码
        Object storedCode = redisService.get(redisKey);
        
        // 验证验证码是否存在且匹配
        if (storedCode != null && code.equals(storedCode.toString())) {
            // 验证成功后删除验证码，防止重复使用
            deleteCode(key);
            return true;
        }
        
        return false;
    }
    
    @Override
    public void deleteCode(String key) {
        String redisKey = CODE_PREFIX + key;
        redisService.delete(redisKey);
    }
    
    /**
     * 生成指定位数的随机数字验证码
     * @param length 验证码长度
     * @return 生成的验证码
     */
    private String generateRandomCode(int length) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
}